<?php


namespace App\Http\Controllers\Admin;


use App\Response\Response;
use Illuminate\Http\Request;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use App\Services\Tools\RedisService;
use App\Http\Controllers\BaseController;

class SuperUserController extends BaseController
{

    /**
     * @api {Get} /super/user 超级管理员权限列表
     * @apiGroup 管理员访问权限
     * @apiParam {Int} page 选填
     * @apiParam {Int} page_size 选填
     * @apiParam {String} nickname 用户昵称 选填
     * @apiParam {Int} mobile 用户手机号 选填
     * @apiParam {Int} user_code 用户编号 选填
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200,
     * "data": {
     * "total": 12566,
     * "current_page": 1,
     * "last_page": 12566,
     * "list": [
     * {
     * "user_id": 547901,
     * "user_code": 250230,
     * "mobile": "15995668093",
     * "nickname（用户昵称）": "崔洪贤",
     * "is_hiding（隐身 1开启 2关闭）": 0,
     * "rank_view（查看排行榜 1开启 2关闭 ）": 0,
     * "remark（备注）": ""
     * }
     * ]
     * },
     * "message": ""
     * }
     */
    public function getSuperUser(Request $request)
    {
        $data = $request->only(['page', 'page_size', 'user_code', 'nickname', 'mobile']);

        $va = app('validator')->make($data, [
            'page'      => 'integer|min:1',
            'page_size' => 'integer|min:1',
            'user_code' => 'integer|min:1',
            'nickname'  => 'string|min:1',
            'mobile'    => 'integer|min:1',
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }
        $data['page_size'] = $data['page_size'] ?? 20;
        $data['page'] = $data['page'] ?? 1;
        $model = app('model_user_config')
            ->where('is_super', 1)
            ->with([
                'userData' => function ($query) {
                    $query->select(['user_id', 'nickname', 'user_code']);
                },
                'user'     => function ($query) {
                    $query->select(['user_id', 'mobile']);
                },
            ]);
        if (!empty($data['nickname'])) {
            $model = $model->whereHas('userData', function ($query) use ($data) {
                $query->where('nickname', 'like', '%' . $data['nickname'] . '%');
            });
        }
        if (!empty($data['user_code'])) {
            $model = $model->whereHas('userData', function ($query) use ($data) {
                $query->where('user_code', '=', $data['user_code']);
            });
        }
        if (!empty($data['mobile'])) {
            $model = $model->whereHas('user', function ($query) use ($data) {
                $query->where('mobile', '=', $data['mobile']);
            });
        }

        $list = $model->paginate($data['page_size'], ['*'], '', $data['page'])->toArray();
        $listData = [];
        foreach ($list['data'] as $key => $value) {
            $listData[$key]['user_id'] = $value['user_id'];
            $listData[$key]['mobile'] = $value['user']['mobile'];
            $listData[$key]['user_code'] = $value['user_data']['user_code'];
            $listData[$key]['nickname'] = $value['user_data']['nickname'];
            $listData[$key]['is_hiding'] = $value['is_hiding'] == 0 ? 2 : 1;
            $listData[$key]['rank_view'] = $value['rank_view'];
            $listData[$key]['remark'] = empty($value['remark']) ? '-' : $value['remark'];
        }
        $result = [
            'total'        => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page'    => $list['last_page'] ?? 1,
            'list'         => $listData,
        ];

        return Response::sendData($result);
    }


    /**
     * @api {get} /super/user/find-super 用户池用选官方账号
     * @apiGroup 管理员访问权限
     * @apiParam {Int} user_code 用户编号 必填
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200,
     * "data": {
     * "user_id": 548199,
     * "nickname": "A.猫痞",
     * "user_code": 330102,
     * "mobile": "17629740982"
     * },
     * "message": ""
     * }
     */
    public function findSuperUser(Request $request)
    {
        $data = $request->only(['user_code']);
        $va = app('validator')->make($data, [
            'user_code' => 'required|integer|min:1',
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }

        $userInfo = app('model_user_data')
            ->select(['user_id', 'nickname', 'user_code'])
            ->where('user_code', $data['user_code'])
            ->with([
                'user' => function ($query) {
                    $query->select(['user_id', 'mobile']);
                },
            ])
            ->whereHas('user', function ($query) {
                $query->where('disabled', 1);
            })
            ->first();

        if (empty($userInfo)) {
            throw  new BasicException(10001, '没有找到此账号，无法设为官方账号!');
        }

        $rdata = [
            'user_id'   => $userInfo['user_id'],
            'nickname'  => $userInfo['nickname'],
            'user_code' => $userInfo['user_code'],
            'mobile'    => $userInfo['user']['mobile'],
        ];

        return Response::sendData($rdata);
    }

    //添加官方账号

    /**
     * @api {post} /super/user 添加官方账号
     * @apiGroup 管理员访问权限
     * @apiParam {Int} user_id 用户编号 选填
     * @apiParam {Int} auth_hiding 账号隐身 选填  1授权 2不授权 （控制客户端是否能够显示账号隐身） 授权后客户端 开关为关的状态
     * @apiParam {Int} auth_rank_view 查看排行榜 选填  1开启 2关闭  不传默认为2
     * @apiParam {String} remark 选填
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":true,"message":""}
     */
    public function setSuperUser(Request $request)
    {
        $data = $request->only(['user_id', 'auth_hiding', 'auth_rank_view', 'remark']);

        $va = app('validator')->make($data, [
            'user_id'        => 'required|integer|min:1',
            'auth_hiding'    => 'filled|in:2,1',//账号隐身
            'auth_rank_view' => 'filled|in:2,1',//查看排行榜
            'remark'         => 'filled|string|max:255',//查看排行榜
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }
        $uData = [
            'is_super'  => 1,
            'rank_view' => $data['auth_rank_view'] ?? 2,
            'is_hiding' => isset($data['auth_hiding']) && $data['auth_hiding'] == 1 ? 2 : 0,//当管理员授予权限时，用户账号隐身默认为关闭状态。
            'is_invisible' => isset($data['auth_hiding']) && $data['auth_hiding'] == 1 ? 1 : 0,//当管理员授予权限时，用户账号隐身默认为关闭状态。
            'remark'    => $data['remark'] ?? '',
        ];


        $isHaveUser = app('model_user')->where('user_id', $data['user_id'])->where('disabled', 1)->first();
        if (empty($isHaveUser)) {
            throw  new BasicException(10001, '没有该用户');
        }

        $isHaveUserConfig = app('model_user_config')->where('user_id', $data['user_id'])->first();
        if (empty($isHaveUserConfig)) {//表中可能没有用户配置
            $uData['user_id'] = $data['user_id'];
            $res = app('model_user_config')->insert($uData);
        } else {
            $res = app('model_user_config')->where('user_id', $data['user_id'])->update($uData);
        }
        RedisService::upUserConfig($data['user_id']);
        if (!$res) {
            throw new BasicException(10001, "没有做出任何修改！");
        }

        return Response::sendData(true);
    }


    /**
     * @api {delete} /super/user 删除官方账号
     * @apiGroup 管理员访问权限
     * @apiParam {Int} user_id 用户编号 选填
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":true,"message":""}
     */
    public function delSuperUser(Request $request)
    {
        $data = $request->only(['user_id']);

        $va = app('validator')->make($data, [
            'user_id' => 'required|integer|min:1',
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }
        $uData = [
            'is_super'  => 0,
            'is_hiding' => 0,
            'rank_view' => 0,
            'remark'    => '',
        ];
        $res = app('model_user_config')->where('user_id', $data['user_id'])->update($uData);

        if (!$res) {
            throw new BasicException(10001, "删除失败！");
        }
        RedisService::upUserConfig($data['user_id']);

        return Response::sendData(true);
    }


}